﻿#ifndef BUSINESSNETWORK_H
#define BUSINESSNETWORK_H

#include <QString>
#include <string>

#include <QJsonObject>
#include <hv/TcpClient.h>

#include <memory>
#include <mutex>
#include "protocol/protocolBuilder.h"
#include "protocol/protocolOption.h"


const int NET_BUFFER_SIZE = 8196 * 2;
class Buffer {
public:
    std::string buffer;
    int64_t totalSize;
    int64_t addedSize;
    Buffer() : buffer(NET_BUFFER_SIZE, '\0'), totalSize(0), addedSize(0) {
    }
};


class BusinessNetWork
{
public:
    // 删除拷贝构造函数和拷贝赋值操作符
    BusinessNetWork(BusinessNetWork const&) = delete;
    BusinessNetWork& operator=(BusinessNetWork const&) = delete;
    // 提供一个全局唯一的接口
    static BusinessNetWork& getInstance();

    // init the tcpclient and transmission protocol setting
    void initNet();

    // get the protocol setting
    std::shared_ptr<ProtocolOption> getProtocolOption();

    // connect to the server
    bool connectTargetServer(const std::string& ip);

    // send message to the server
    void sendMessageToServer(int type, int subtype, int64_t id1, int64_t id2, int64_t id3, unsigned char* data, int length, bool initClient = false);

    // request a id from server
    uint64_t requestUniqueID();

    // new net connection
    void newNetConnection(const hv::SocketChannelPtr& channel);
    // deleteConnection
    void deleteNetConnection(const hv::SocketChannelPtr& channel);
    // get channelBuffer
    std::shared_ptr<Buffer> getChannelBuffer(const hv::SocketChannelPtr& channel);



private:
    BusinessNetWork();

    // login target server(reconnect used)
    bool loginTargetServer(const std::string& account, const std::string& password);
    // protocolOption
    std::shared_ptr<ProtocolOption> protoOpt;
    // buffer, total size, added size
    std::map<hv::SocketChannelPtr, std::shared_ptr<Buffer>> channelBuffer;

    std::mutex sendLock;
};

#endif // BUSINESSNETWORK_H
